package geyue.wechat;

import java.awt.EventQueue;
import java.io.File;

import javax.swing.UIManager;

import com.blade.kit.DateKit;
import com.blade.kit.StringKit;
import com.blade.kit.http.HttpRequest;
import com.blade.kit.json.JSONObject;

import geyue.wechat.exception.WechatException;
import geyue.wechat.listener.WechatListener;
import geyue.wechat.model.WechatMeta;
import geyue.wechat.service.WechatService;
import geyue.wechat.service.WechatServiceImpl;
import geyue.wechat.ui.QRCodeFrame;
import geyue.wechat.util.CookieUtil;
import geyue.wechat.util.Matchers;

public class WechatRobot {

	private int tip = 0;
	private WechatListener wechatListener = new WechatListener();
	private WechatService wechatService = new WechatServiceImpl();
	private WechatMeta wechatMeta = new WechatMeta();

	private QRCodeFrame qrCodeFrame;

	public WechatRobot() {
		System.setProperty("https.protocols", "TLSv1");
		System.setProperty("jsse.enableSNIExtension", "false");
	}

	/**
	 * 显示二维码
	 * 
	 * @return 网络协议有哪几种，在微信中都用到了哪些
	 */
	public void showQrCode() throws WechatException {
		// 获取uuid
		String uuid = wechatService.getUUID();

		wechatMeta.setUuid(uuid);
		System.out.println("获取到uuid为 [{}]" + uuid);

		String url = Constant.QRCODE_URL + uuid;

		final File output = new File("temp.jpg");

		HttpRequest.post(url, true, "t", "webwx", "_",
				DateKit.getCurrentUnixTime()).receive(output);

		if (null != output && output.exists() && output.isFile()) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						UIManager
								.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
						qrCodeFrame = new QRCodeFrame(output.getPath());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	/**
	 * 等待登录
	 */
	public String waitForLogin() throws WechatException {
		this.tip = 1;
		String url = "https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login";// 网址的结果是window.code=400;
		HttpRequest request = HttpRequest
				.get(url, true, "tip", this.tip, "uuid", wechatMeta.getUuid(),
						"_", DateKit.getCurrentUnixTime());

		System.out.println("等待登录...");
		System.out.println("阿杰111" + request);
		System.out.println("阿杰" + request.toString());

		String res = request.body();
		
		request.disconnect();

		if (null == res) {
			throw new WechatException("扫描二维码验证失败");
		}

		// 用来获取微信服务器发出的一个code，通过这个code可以判断用户是否登录成功
		String code = Matchers.match("window.code=(\\d+);", res);

		if (null == code) {
			throw new WechatException("扫描二维码验证失败");
		} else {
			if (code.equals("201")) {
System.out.println("成功扫描,请在手机上点击确认以登录");
				tip = 0;
			} else if (code.equals("200")) {
System.out.println("正在登录...");

				String pm = Matchers.match("window.redirect_uri=\"(\\S+?)\";",
						res);
				String redirect_uri = pm + "&fun=new";

System.out.println( redirect_uri);

				wechatMeta.setRedirect_uri(redirect_uri);

				String base_uri = redirect_uri.substring(0,
						redirect_uri.lastIndexOf("/"));
				wechatMeta.setBase_uri(base_uri);

				System.out.println("redirect_uri={}" + redirect_uri);
				System.out.println("base_uri={}" + base_uri);

			} else if (code.equals("408")) {
				throw new WechatException("登录超时");
			} else {
				System.out.println("扫描code={}" + code);

			}
		}
		return code;
	}

	public void closeQrWindow() {
		// dispose()释放由此 Window、其子组件及其拥有的所有子组件所使用的所有本机屏幕资源。
		qrCodeFrame.dispose();

	}

	/**
	 * 登录
	 */
	public void login() throws WechatException {

		HttpRequest request = HttpRequest.get(wechatMeta.getRedirect_uri());

		System.out.println("阿杰1" + request);

		String res = request.body();

		wechatMeta.setCookie(CookieUtil.getCookie(request));
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("登录失败");
		}

		wechatMeta.setSkey(Matchers.match("<skey>(\\S+)</skey>", res));
		wechatMeta.setWxsid(Matchers.match("<wxsid>(\\S+)</wxsid>", res));
		wechatMeta.setWxuin(Matchers.match("<wxuin>(\\S+)</wxuin>", res));
		wechatMeta.setPass_ticket(Matchers.match(
				"<pass_ticket>(\\S+)</pass_ticket>", res));

		/*
		 * JSONObject 就是常说的 json,是一种重要的数据传输对象,
		 * 其格式为{"key1":value1,"key2",value2....};key 必须是字符串。
		 * 
		 */
		JSONObject baseRequest = new JSONObject();

		baseRequest.put("Uin", wechatMeta.getWxuin());
		baseRequest.put("Sid", wechatMeta.getWxsid());
		baseRequest.put("Skey", wechatMeta.getSkey());
		baseRequest.put("DeviceID", wechatMeta.getDeviceId());
		
		wechatMeta.setBaseRequest(baseRequest);
		
		System.out.println("skey [{}]" + wechatMeta.getSkey());
		System.out.println("wxsid [{}]" + wechatMeta.getWxsid());
		System.out.println("wxuin [{}]" + wechatMeta.getWxuin());
		System.out.println("pass_ticket [{}]" + wechatMeta.getPass_ticket());

		File output = new File("temp.jpg");
		if (output.exists()) {
			output.delete();
		}
	}

	public void start() throws WechatException {

		this.login();
		System.out.println("微信登录成功");
		System.out.println("微信初始化...");

		wechatService.wxInit(wechatMeta);
		System.out.println("微信初始化成功");
		System.out.println("开启状态通知...");
		System.out.println("开启状态通知...");

		wechatService.openStatusNotify(wechatMeta);
		System.out.println("开启状态通知成功");
		System.out.println("获取联系人...");
		
		Constant.CONTACT = wechatService.getContact(wechatMeta);
		System.out.println("获取联系人成功");
		System.out.println("共有 {} 位联系人"+ Constant.CONTACT.getContactList().size());

		// 监听消息
		wechatListener.start(wechatService, wechatMeta);
	}

}